import axios from 'axios';
import { Toast } from 'antd-mobile';
import { getToken, logout } from './utils';

const baseURL = '/api';

axios.defaults.baseURL = baseURL;
axios.defaults.timeout = 60000;

const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const fetch = axios.create();

const setHeaders = (headers = {}) => {
  fetch.defaults.headers = Object.assign(fetch.defaults.headers, headers);
};

const beforeReq = (fn, errFn) => {
  fetch.interceptors.request.use(
    (config) => {
      config.cancelToken = source.token;
      config.source = source;
      const cfg = fn && fn(config);
      if (cfg) return cfg;
      return config;
    },
    (error) => {
      errFn && errFn();
      return Promise.reject(error);
    },
  );
};

const beforeRes = (fn, errFn) => {
  fetch.interceptors.response.use(
    (res) => {
      const rzlt = fn && fn(res.data);
      if (rzlt) return rzlt;
      return res.data;
    },
    (error) => {
      errFn && errFn(error);
      return Promise.reject(error);
    },
  );
};

const init = () => {
  (global || window).fetch = fetch;
  fetch.axios = axios;
};

let requestUrl;
let isDev = process.env.RUN_ENV !== 'pro';
// let token = getToken();
// if (token) setHeaders({ token });
const loadingIcon = require('/public/imgs/loading.gif');

beforeReq(
  (cfg) => {
    if (cfg.reqOnece && requestUrl === cfg.url)
      cfg.source.cancel('Operation canceled by the user.');
    if (cfg.reqOnece) requestUrl = cfg.url;
    if (!cfg.noLoading) Toast.info(<img src={loadingIcon} alt="Loading" />, 60);

    return cfg;
  },
  () => {
    Toast.hide();
  },
);

beforeRes(
  (res) => {
    requestUrl = '';
    Toast.hide();

    // if (res.code === '1004') logout();
  },
  (err) => {
    // 还原requestUrl, 避免一次网络错误后，自动取消接下来的请求
    requestUrl = '';

    !isDev && Toast.hide();
    isDev && Toast.info(err.response.data);
    if (!err || !err.response) {
      return Toast.info('网络不通畅，请重试', 3);
    }
    if (err.response.status === 401) {
      // logout();
    }
  },
);

init();

export default {
  init,
  setHeaders,
  beforeReq,
  beforeRes,
};
